package cn.kgc.vue.service.impl;

import cn.kgc.vue.commons.QueryCondition;
import cn.kgc.vue.entity.User;
import cn.kgc.vue.mapper.UserMapper;
import cn.kgc.vue.response.ResponseResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.kgc.vue.entity.Dept;
import cn.kgc.vue.service.DeptService;
import cn.kgc.vue.mapper.DeptMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author mengshun
* @description 针对表【sys_dept】的数据库操作Service实现
* @createDate 2024-09-24 10:42:24
*/
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements DeptService{

    @Resource
    private UserMapper userMapper;

    @Override
    public ResponseResult deptPage(QueryCondition<Dept> queryCondition) {

        Page<Dept> deptPage = new Page<>(queryCondition.getPage(), queryCondition.getLimit());
        Dept searchParams = queryCondition.getSearchParams();
        String deptName = searchParams.getDeptName();

        LambdaQueryWrapper<Dept> lambda = new QueryWrapper<Dept>().lambda();
        lambda.like(StringUtils.isNotBlank(deptName),Dept::getDeptName,deptName)
                .orderByDesc(Dept::getCreateTime);

        baseMapper.selectPage(deptPage,lambda);

        return ResponseResult.success()
                .data("total",deptPage.getTotal())
                .data("tableData",deptPage.getRecords());
    }

    @Override
    public ResponseResult delteDept(Integer id) {

        //  1. 判定删除的部门是否含有员工
        LambdaQueryWrapper<User> lambda = new QueryWrapper<User>().lambda();
        lambda.eq(User::getDeptId,id);
        List<User> users = userMapper.selectList(lambda);

        if (ObjectUtils.isNotNull(users)){
            return  ResponseResult.fail().message("部门存在员工,不能删除");
        }

        // 2. 删除部门信息
        baseMapper.deleteById(id);

        return ResponseResult.success();
    }
}




